{
 "cells": [
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": "# 获取大模型",
   "id": "b51eb4ade4f7aeab"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T12:10:15.894892Z",
     "start_time": "2025-10-26T12:10:14.759063Z"
    }
   },
   "cell_type": "code",
   "source": [
    "import dotenv\n",
    "import os\n",
    "\n",
    "import langchain.chains.llm\n",
    "import langchain.chains.sequential\n",
    "import langchain_core.prompts\n",
    "from langchain_openai import ChatOpenAI, OpenAI\n",
    "\n",
    "dotenv.load_dotenv()\n",
    "\n",
    "os.environ[\"OPENAI_API_KEY\"] = os.getenv(\"OPENAI_API_KEY\")\n",
    "os.environ[\"OPENAI_API_BASE\"] = os.getenv(\"OPENAI_BASE_URL\")\n",
    "CHAT_MODEL = ChatOpenAI(\n",
    "    model=\"gpt-4o-mini\"\n",
    ")\n",
    "\n",
    "llm = OpenAI(\n",
    "    model=\"gpt-4o-mini\",\n",
    ")"
   ],
   "id": "d6951132e94287c2",
   "outputs": [],
   "execution_count": 1
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "# 基于LCEL构建的Chains的类型\n",
    "create_sql_query_chain\n",
    "create_stuff_documents_chain\n",
    "create_openai_fn_runnable\n",
    "create_structured_output_runnable\n",
    "load_query_constructor_runnable\n",
    "create_history_aware_retriever\n",
    "create_retrieval_chain"
   ],
   "id": "fef64f08a37c78e"
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## create_sql_query_chain\n",
    "`create_sql_query_chain`，**SQL查询链**，是创建生成SQL查询的链，用于将 自然语言 转换成 数据库的SQL查询\n",
    "\n",
    "这里使用MySQL数据库，需要安装pymysql\n",
    "> pip install pymysql"
   ],
   "id": "69318bb8f995a38d"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T13:10:33.303928Z",
     "start_time": "2025-10-26T13:10:33.272912Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain_community.utilities import SQLDatabase\n",
    "from urllib.parse import quote_plus\n",
    "\n",
    "db_user = \"root\"\n",
    "db_password = \"Answer123@\"\n",
    "db_host = \"127.0.0.1\"\n",
    "db_port = \"3306\"\n",
    "db_name = \"test_db\"\n",
    "\n",
    "encoded_pwd = quote_plus(db_password)\n",
    "db = SQLDatabase.from_uri(\n",
    "    f\"mysql+pymysql://{db_user}:{encoded_pwd}@{db_host}:{db_port}/{db_name}\"\n",
    ")\n",
    "\n",
    "print(\"哪种数据库：\", db.dialect)\n",
    "print(\"获取数据表：\", db.get_usable_table_names())\n",
    "res = db.run(\"SELECT count(*) FROM employee;\")\n",
    "print(\"查询结果：\", res)"
   ],
   "id": "a34b1126ee8dabd0",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "哪种数据库： mysql\n",
      "获取数据表： ['employee']\n",
      "查询结果： [(2,)]\n"
     ]
    }
   ],
   "execution_count": 7
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T13:36:01.576605Z",
     "start_time": "2025-10-26T13:35:59.375211Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.chains.sql_database.query import create_sql_query_chain\n",
    "\n",
    "# 调用Chain\n",
    "chain = create_sql_query_chain(llm=llm, db=db)\n",
    "# # 限制使用的表\n",
    "response = chain.invoke({\"question\": \"一共有多少个员工？\", \"table_names_to_use\":\n",
    "    [\"employee\"]})\n",
    "print(response)"
   ],
   "id": "849dceaae54271c9",
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "SQLQuery: SELECT COUNT(*) AS `employee_count` FROM `employee`\n"
     ]
    }
   ],
   "execution_count": 9
  },
  {
   "metadata": {},
   "cell_type": "markdown",
   "source": [
    "## create_stuff_documents_chain(了解)\n",
    "`create_stuff_documents_chain` 用于将 **多个文档内容** 合并成 **单个长文本** 的链式工具，并一次性传递给LLM处理（而不是分多次处理）。\n",
    "\n",
    "适合场景：\n",
    "- 保持上下文完整，适合需要全局理解所有文档内容的任务（如总结、问答）\n",
    "- 适合处理 **少量/中等长度文档** 的场景。"
   ],
   "id": "26ed5776c8fb22c6"
  },
  {
   "metadata": {
    "ExecuteTime": {
     "end_time": "2025-10-26T14:17:16.189562Z",
     "start_time": "2025-10-26T14:17:14.041903Z"
    }
   },
   "cell_type": "code",
   "source": [
    "from langchain.chains.combine_documents import create_stuff_documents_chain\n",
    "from langchain_core.prompts import PromptTemplate\n",
    "from langchain_core.documents import Document\n",
    "\n",
    "# 定义提示词模板\n",
    "prompt = PromptTemplate.from_template(\"\"\"\n",
    "如下文档{docs}中说，香蕉是什么颜色的？\n",
    "\"\"\")\n",
    "# 创建链\n",
    "chain = create_stuff_documents_chain(llm, prompt, document_variable_name=\"docs\")\n",
    "# 文档输入\n",
    "docs = [\n",
    "    Document(\n",
    "        page_content=\"苹果，学名Malus pumila Mill.，别称西洋苹果、柰，属于蔷薇科苹果属的植物。苹果是全球最广泛种植和销售的水果之一，具有悠久的栽培历史和广泛的分布范围。苹果的原始种群主要起源于中亚的天山山脉附近，尤其是现代哈萨克斯坦的阿拉木图地区，提供了所有现代苹果品种的基因库。苹果通过早期的贸易路线，如丝绸之路，从中亚向外扩散到全球各地。\"\n",
    "    ),\n",
    "    Document(\n",
    "        page_content=\"香蕉是白色的水果，主要产自热带地区。\"\n",
    "    ),\n",
    "    Document(\n",
    "        page_content=\"蓝莓是蓝色的浆果，含有抗氧化物质。\"\n",
    "    )\n",
    "]\n",
    "# 执行摘要\n",
    "chain.invoke({\"docs\": docs})\n"
   ],
   "id": "64b97877fdb1cddf",
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'香蕉是白色的水果。'"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "execution_count": 10
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
